#include "BagManager.h"
#include <cmath>


BagManager::BagManager( )
{
	int curX = 0;
	int curY = 0;

	for( int l = 0; l < ClientSettings::BAG_NLINES; l++)
	{
		curX = 0;
		for( int c=0; c < ClientSettings::BAG_NCOLS; c++)
		{
			mBag[l][c] = new TileBag(ClientSettings::BAG_POS_X + curX, ClientSettings::BAG_POS_Y + curY, l, c);
			curX += ClientSettings::TILE_BAG_SIZE + ClientSettings::BAG_INTERVALS;
		}
		curY += ClientSettings::TILE_BAG_SIZE + ClientSettings::BAG_INTERVALS;
	}

	mFont = CreateFont(ClientSettings::BAG_LETTERS_SIZE,0,0,0,FW_BOLD,FALSE,FALSE,FALSE,DEFAULT_CHARSET,OUT_OUTLINE_PRECIS,
						CLIP_DEFAULT_PRECIS,CLEARTYPE_QUALITY, VARIABLE_PITCH,TEXT("Comic Sans"));
}


BagManager::~BagManager(void)
{
	DeleteObject(mFont);

	// Apaga os tiles
	for( int l = 0; l < ClientSettings::BAG_NLINES; l++)
		for( int c=0; c < ClientSettings::BAG_NCOLS; c++)
		delete mBag[l][c];

}

void BagManager::Render( HDC _surface )
{
	// Aplica a nova fonte do board
	HFONT hfOld = static_cast<HFONT>(SelectObject(_surface, mFont));

	for( int l = 0; l < ClientSettings::BAG_NLINES; l++)
		for( int c=0; c < ClientSettings::BAG_NCOLS; c++)
			mBag[l][c]->Render(_surface);

	// Aplica a fonte que vinha na surface
	SelectObject(_surface, hfOld);
}

DWORD BagManager::getArrayCoordsFromPoint( int _x, int _y )
{
	for( int l = 0; l < ClientSettings::BAG_NLINES; l++)
		for( int c=0; c < ClientSettings::BAG_NCOLS; c++)
			if( mBag[l][c]->ContainsPoint(_x, _y) )
				return TILE_ARRAY_COORDS(l, c);

	return INVALID_TILE_COORDS;
}

TileBag* BagManager::getTileFromCoords( int _line, int _col )
{
	if( _line >= ClientSettings::BAG_NLINES || _line < 0 || _col < 0 || _col >= ClientSettings::BAG_NCOLS)
		return NULL;

	return mBag[_line][_col];
}

void BagManager::LockTile( int _line, int _col )
{
	mBag[_line][_col]->State().Set(TileState::INACTIVE);
}

void BagManager::UnlockTile( int _line, int _col )
{
	mBag[_line][_col]->State().Set(TileState::ACTIVE);
}

void BagManager::PlaceLetter( UINT _line, UINT _col, char _letter )
{
	mBag[_line][_col]->Letter(_letter);
}

void BagManager::Reset()
{
	for( int l = 0; l < ClientSettings::BAG_NLINES; l++)
		for( int c=0; c < ClientSettings::BAG_NCOLS; c++)
			mBag[l][c]->State().Set(TileState::ACTIVE);
}
